﻿using System.Collections.Generic;
using LogSystem;
using UnityEngine;
using XLua;
#if UNITY_EDITOR
using UnityEditor;
#endif

namespace ImageEffects
{
    public class LightElement : MonoBehaviour
    {
        [Header("是否复制材质，当一种人物模型同时出现在多种灯光下需要勾选")]
        public bool CloneMaterial;

        public List<Renderer> LightRenderers;
        #if UNITY_EDITOR
        [BlackList]
        public List<Material> LightMaterials { get; set; }
        #endif
        [SerializeField]
        protected LightController _lightController;

        protected bool _isAdded = false;

        [Header("有值时会自动找到指定mark的LightController")]
        public string controllerMark;
        
        [HideInInspector]
        public MaterialPropertyBlock propertyBlock { get; set; }
        
        public void OnSetController(LightController lightController)
        {
            _lightController = lightController;
            _isAdded = true;
        }

        public void OnEnable()
        {
            AddToLightController();
        }

        public void OnRemoved()
        {
            _isAdded = false;
#if UNITY_EDITOR
            LightMaterials = null;
#endif
            _lightController = null;
        }

        private void OnDestroy()
        {
            if (_isAdded)
            {
                _lightController.RemoveLightingElement(this);
            }
        }

        protected void AddToLightController()
        {
            if (!string.IsNullOrEmpty(controllerMark))
            {
                LightController.lightControllerMap.TryGetValue(controllerMark, out LightController lightController);
                if (lightController)
                {
                    lightController.AddLightElement(this);   
                }
                else
                {
#if  UNITY_EDITOR
                    Debug.LogError(LogModule.LibertyScene,$"【Editor日志】没有这个LightController：{controllerMark},请确保LightElement的controllerMark正确！！！",transform.gameObject);
#endif
                }
            }
        }


#if UNITY_EDITOR

        [BlackList]
        public void FindLightRenderer(bool autoSave = true)
        {
            LightRenderers = new List<Renderer>();

            var allRenderers = transform.GetComponentsInChildren<Renderer>();

            if (allRenderers==null)
            {
                return;
            }
            
            for (int i = 0; i < allRenderers.Length; i++)
            {
                var item = allRenderers[i];
                var sharedMaterial = item.sharedMaterials;
                if (sharedMaterial == null)
                {
                    Debug.LogError(LogModule._Default_, $"Renderer({item})没有材质", item);
                    continue;
                }

                foreach (var material in sharedMaterial)
                {
                    if (material!=null && material.HasProperty("_MainLightCol"))
                    {
                        LightRenderers.Add(item);
                    }
                }
            }

            if (autoSave)
            {
                var stage = UnityEditor.SceneManagement.
                    PrefabStageUtility.GetCurrentPrefabStage();
                var prefab = PrefabUtility.GetNearestPrefabInstanceRoot(this.gameObject);
                if (prefab != null)
                {
                    if (stage == null)
                    {
                        PrefabUtility.ApplyPrefabInstance(prefab, InteractionMode.AutomatedAction);
                        Selection.activeGameObject = gameObject;
                        //EditorSceneManager.SaveScene(SceneManager.GetActiveScene());
                    }
                    else
                    {
                        EditorUtility.SetDirty(prefab);
                    }

                }
                else
                {
                    if (stage != null)
                        EditorUtility.SetDirty(gameObject);
                    else
                        PrefabUtility.SavePrefabAsset(gameObject);
                }
            }
          
        }
        
        //[BlackList]

//        private void OnValidate()
//        {
//            if (LightRenderers == null || LightRenderers.Count == 0)
//            {
//                return;
//            }
//            
//            for (int i = LightRenderers.Count - 1; i <= 0; i--)
//            {
//                if (LightRenderers[i])
//                {
//                    if (!LightRenderers[i].sharedMaterial.HasProperty("_MainLightColor"))
//                    {
//                        Debug.LogError("存在错误Renderer");
//                    }
//                }
//            }
//        }
#endif

    }

}
